<template>
	<view class="um-code-input">
		<input type="number" :key="key" v-for="(item,key) in inputs" :id="'code'+key" class="code" maxlength="1"
			@input="(event: any)=>handleInput(key, event)" :focus="item.focus" v-model="item.value">
	</view>
</template>

<script lang="ts" setup>
	import { reactive } from 'vue';

	const inputs = reactive([
		{ focus: false, value: "" },
		{ focus: false, value: "" },
		{ focus: false, value: "" },
		{ focus: false, value: "" },
	])
	const emits = defineEmits(['input'])

	const focus = (index : number) => {
		for (let i = 0; i < inputs.length; i++) {
			inputs[i].focus = false
		}
		inputs[index].focus = true
	}

	const handleInput = (key : number, event : any) => {
		emits("input", inputs.map((item) => (item.value)).join(""))
		if (event.detail.value === "") {
			if (key === 0) {
				return
			}
			focus(key - 1)
		} else {
			if (key === inputs.length - 1) {
				return
			}
			focus(key + 1)
		}
	}
</script>

<style lang="scss" scoped>
	.um-code-input {
		display: flex;
		gap: 20rpx;

		.code {
			font-size: 48rpx;
			border-radius: 10rpx;
			width: 100rpx;
			height: 100rpx;
			text-align: center;
			border: 1rpx solid #ccc;
		}
	}
</style>